
import os


import cv2
import numpy as np
abcd = 1000


## 没写完，不用了，用get_map
def saveResult(dir_save_path, fileName, yolo, image, class_names):
    out_boxes, out_scores, out_classes = yolo.detect_myImage(image)

    if not os.path.exists(dir_save_path):
        os.makedirs(dir_save_path)

    file_save_name = os.path.join(dir_save_path, fileName);
    file_save = open(file_save_name, 'w', encoding='utf-8')

    for i, c in enumerate(out_classes):
        predicted_class = class_names[int(c)]
        try:
            score = str(out_scores[i].numpy())
        except:
            score = str(out_scores[i])

        top, left, bottom, right = out_boxes[i]

def isChangeLabel(boxes, nw, nh, w, h, ratio_up = 0.75, ratio_low = 0.1):
    ##不用管是否超出边界，后面有步骤去除，因为 矩形边 会出现负数被筛掉
    if (np.array([nw,nh]) <= np.array([w, h])).all():
        return False, None, None

    # ins1 = boxes[:, 0:2] >= 0  ##大部分图片都会超，这个判断就有点多余
    # if ins1.all():
    #     ins2 = boxes[:, 2:4] <= [w, h]
    #     if ins2.all():
    #         return False, None

    ww = [0, 0, w, h]
    wcoord = np.maximum(boxes[:, 0:2], ww[0:2])
    hcoord = np.minimum(boxes[:, 2:4], ww[2:4])

    inarea = np.prod(hcoord - wcoord, axis=1)
    area = np.prod(boxes[:, 2:4] - boxes[:, 0:2], axis=1)
    ratio = inarea / area

    ins2 = ratio >= ratio_low
    ins = np.logical_and(ratio < ratio_up, ins2)
    return True, ins, ins2

def test():
    image_data = cv2.imread('test.jpg')
    boxes = np.load('databox.npy')

    isChangeLabel(boxes, 900, 900, 800, 800)

    print(boxes)
    # cv2.imshow('aa', image_data)
    #
    # for box in boxes:
    #     label = box[4]
    #
    #     box = box[0:4]
    #
    #     if label == 0:
    #         cv2.rectangle(image_data, (box[0], box[1]), (box[2], box[3]), (0, 0, 255), 2)
    #     elif label == 1:
    #         cv2.rectangle(image_data, (box[0], box[1]), (box[2], box[3]), (255, 0, 0), 2)
    #     elif label == 2:
    #         cv2.rectangle(image_data, (box[0], box[1]), (box[2], box[3]), (0, 0, 0), 2)
    #     else:
    #         print('error....')
    # cv2.imshow('aa', image_data)
    # cv2.waitKey(0)

    ww = [0, 0, 799, 799]
    wcoord = np.maximum(boxes[:, 0:2], ww[0:2])
    hcoord = np.minimum(boxes[:, 2:4], ww[2:4])

    inarea = np.prod(hcoord - wcoord, axis=1)
    area = np.prod(boxes[:, 2:4] - boxes[:, 0:2], axis=1)
    ratio = inarea/area
    print(wcoord, hcoord, inarea, area)
    print(ratio)


def ttttt():
    global abcd
    print(abcd)
    abcd = 11
    print(abcd)

if __name__== "__main__" :
    # test()
    ttttt()
    input()

    from nets.yolo import get_train_model, yolo_body
    from nets.yolo_training import get_lr_scheduler
    from utils.callbacks import LossHistory, ModelCheckpoint, EvalCallback
    from utils.dataloader import YoloDatasets
    from utils.utils import get_anchors, get_classes, show_config
    from utils.utils_fit import fit_one_epoch

    # import sys
    # sys.exit(0)
    train_annotation_path = 'to_train2.txt'
    input_shape = [800, 800]
    anchors_path = 'model_data/yolo_anchors.txt'

    anchors, num_anchors = get_anchors(anchors_path)
    batch_size = 12
    classes_path = '=tobacco/leaf_clasees.txt'
    class_names, num_classes = get_classes(classes_path)
    anchors_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
    Init_Epoch = 0
    UnFreeze_Epoch = 200
    mosaic = False
    train = True

    with open(train_annotation_path, encoding='utf-8') as f:
        train_lines = f.readlines()
    num_train = len(train_lines)

    train_dataloader = YoloDatasets(train_lines, input_shape, anchors, batch_size, num_classes, anchors_mask,
                                    Init_Epoch, UnFreeze_Epoch, mosaic=mosaic, train=True)
    image_data, y_true0, y_true1, y_true2, boxes = train_dataloader.testGenerate()




    print(y_true0.shape, y_true1.shape, y_true2.shape)

    for img, bbb in zip(image_data, boxes):
    # img = image_data[0]
    # for box in boxes[0]:
        for box in bbb:
            label = box[4]

            box = box[0:4]

            if label == 0:
                cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 0, 255), 2)
            elif label == 1:
                cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (255, 0, 0), 2)
            elif label == 2:
                cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 0, 0), 2)
            else:
                print('error....')

    cv2.imshow('aa', img)
    cv2.waitKey(0)
    print('done')